<?php
/**
 * Created by PhpStorm.
 * User: xding
 * Date: 15/10/16
 * Time: 下午3:15
 */

class Relationships_model extends CI_Model {

    private $tb_name         = 'relationships';
    private $type_verify     = array('category','tag','nav_menu');
    private $type            = NULL;

    private $sort_key        = 'object_id'; // 默认排序字段
    private $sort_type       = 'ASC'; // 默认排序方式
    private $sort_key_verify = array('object_id','relation_id');


    private $relationships   = NULL;
    private $init_status     = 0;

    public function __construct() {
        parent::__construct();
        $this->load->database();
    }

    /**
     * 此处在Relationship模型初始化开始时
     * 将所有的记录读出，存储到$relationships对象数组中
     *
     * 这样做得目的是：
     * 1、避免频繁读取数据库
     * 隐患：当relationships表记录极大时，
     * 将会对内存有所影响，不过relationships表字段结构较为简单
     *
     * 如果后期采用了缓存，可以将其存入缓存
     */
    public function initialize($type) {

        if (empty($type) || !in_array($type,$this->type_verify))
        {
            throw new Exception('please execute initialize method and put the necessary and right param, like $this->relationships->initialize("category")');
        }

        $this->db->where('type',$type);
        $this->db->order_by("{$this->sort_key} {$this->sort_type}");
        $query = $this->db->get($this->tb_name);
        $this->relationships = $query->result_array();

        $this->type          = $type;
        $this->init_status   = 1;

        return $this;
    }


    /**
     * sort relationship
     *
     * @param $sort_key
     * @param string $sort_type
     * @return $this
     * @throws
     */
    public function sort($sort_key,$sort_type = 'ASC') {

        if (!$this->init_status)
            throw new Exception('please initialize by initialize() method if you want to use it');

        if (!in_array($sort_key,$this->sort_key_verify))
            throw new Exception('sort key is not exists');

        // 默认按照 object_id 升序排序，无须再排，直接返回
        if ( $sort_key === $this->sort_key && $sort_type === $this->sort_type )
        {
            return $this;
        }

        $this->sort_key  = $sort_key;
        $this->sort_type = $sort_type;

        // 此处使用匿名函数
        usort($this->relationships, function($a,$b){
            if ( $a[$this->sort_key] == $b[$this->sort_key] )
                return 0;
            if ( 'ASC' === $this->sort_type)
                return ($a[$this->sort_key] > $b[$this->sort_key]) ? 1 : -1;
            return ($a[$this->sort_key] > $b[$this->sort_key]) ? -1 : 1;
        });

        return $this;
    }


    public function get_object_ids($relation_id) {

        if (!$this->init_status)
            throw new Exception('please initialize by initialize() method if you want to use it');

        $ids_array = array();
        foreach ( $this->relationships as $row )
        {
            if ( $row['relation_id'] == $relation_id )
                array_push($ids_array,$row['object_id']);
        }

        return $ids_array;
    }


    public function get_relation_ids($object_id) {

        if (!$this->init_status)
            throw Exception('please initialize by initialize() method if you want to use it');

        if ( 'object_id' !== $this->sort_key )
        {
            $this->sort('object_id');
        }

        $ids_array = array();
        foreach ( $this->relationships as $row )
        {
            if ( $row['object_id'] > $object_id )
                break;

            if ( $row['object_id'] == $object_id )
                array_push($ids_array,$row['relation_id']);

        }

        return $ids_array;
    }


    /**
     * 插入relationships
     *
     * @param $relationships  Array( \Beans\Relationship )
     * @return bool
     */
    public function insert_relationship($relationships) {

        if ( ! is_array($relationships) )
        {
            return FALSE;
        }

        // 采用批量插入数据，减少数据库访问次数。更新数据后将初始化状态置为0
        return $this->db->insert_batch(\Beans\Relationship::$_TB_NAME,$relationships) &&
               ! ($this->init_status = 0);
    }


    /**
     * 更新relationships
     *
     * @param $relationships
     * @return bool
     */
    public function update_relationshp($relationships)
    {
        if ( ! is_array($relationships) ) return FALSE;
        return $this->db->update_betch(\Beans\Post::$_TB_NAME,$relationships) &&
               ! ( $this->init_status = 0 );
    }



    /**
     * delete relationship
     *
     * @param $conditions array( array( "key" => "object_id", "value" => 1, "method" => "where" ), ... )
     * @return bool
     */
    public function delete_relationship($conditions) {

        if ( !$conditions && !is_array($conditions) )
        {
            return FALSE;
        }

        foreach ( $conditions as $key => $val )
        {
            $method = $val['method'] ?: 'where';
            $this->db->$method($val['key'],$val['value']);
        }

        return $this->db->delete(\Beans\Relationship::$_TB_NAME);
        //dump($this->db->last_query());
    }
}